use ggez::{Context, GameResult};
use ggez::graphics;

pub struct Map {
    width: usize,
    height: usize,
    tiles: Vec<Vec<TileType>>,
}

#[derive(Clone, Copy)]
pub enum TileType {
    Empty,
    Wall,
    DestructibleWall,
}

impl Map {
    pub fn new(width: usize, height: usize) -> Self {
        let mut tiles = vec![vec![TileType::Empty; height]; width];
        
        // 创建边界墙
        for x in 0..width {
            tiles[x][0] = TileType::Wall;
            tiles[x][height - 1] = TileType::Wall;
        }
        
        for y in 0..height {
            tiles[0][y] = TileType::Wall;
            tiles[width - 1][y] = TileType::Wall;
        }
        
        // 随机添加一些可破坏的墙
        use rand::Rng;
        let mut rng = rand::thread_rng();
        for _ in 0..30 {
            let x = rng.gen_range(1..width - 1);
            let y = rng.gen_range(1..height - 1);
            tiles[x][y] = TileType::DestructibleWall;
        }
        
        Self { width, height, tiles }
    }
    
    pub fn draw(&self, canvas: &mut graphics::Canvas, ctx: &mut Context) -> GameResult {
        let tile_size = 30.0;
        
        for x in 0..self.width {
            for y in 0..self.height {
                let color = match self.tiles[x][y] {
                    TileType::Empty => graphics::Color::from([0.1, 0.2, 0.3, 1.0]),
                    TileType::Wall => graphics::Color::from([0.5, 0.5, 0.5, 1.0]),
                    TileType::DestructibleWall => graphics::Color::from([0.8, 0.4, 0.2, 1.0]),
                };
                
                let rect = graphics::Rect::new(
                    x as f32 * tile_size,
                    y as f32 * tile_size,
                    tile_size,
                    tile_size,
                );
                
                let mesh = graphics::Mesh::new_rectangle(
                    ctx,
                    graphics::DrawMode::fill(),
                    rect,
                    color,
                )?;
                
                canvas.draw(&mesh, graphics::DrawParam::default());
            }
        }
        
        Ok(())
    }
    
    pub fn check_collision(&self, position: (f32, f32)) -> bool {
        let tile_size = 30.0;
        let x = (position.0 / tile_size) as usize;
        let y = (position.1 / tile_size) as usize;
        
        if x < self.width && y < self.height {
            match self.tiles[x][y] {
                TileType::Wall | TileType::DestructibleWall => true,
                TileType::Empty => false,
            }
        } else {
            true // 边界外也视为碰撞
        }
    }
}